import { defineStore } from "pinia";
import { get_menu, login, recordLog } from "@/api/login.js";
import { showMessage } from "@/utils/Message";
import { getDetailedInfo, getIpAddress } from "@/utils/Common.js";

export const userStore = defineStore({
  id: "user",
  state: () => ({
    userinfo: {},
    token: undefined,
    refresh: undefined,
    menus: [],
    routerResult: [],
    role: "",
  }),
  actions: {
    // 登录并获取用户信息和token
    async LoginUser(userinfo) {
      try {
        const { userinfo: user, token, refresh, role } = await login(userinfo);
        this.userinfo = user;
        this.token = token;
        this.refresh = refresh;
        this.role = role;
        showMessage("success", "登录成功");
        return { type: true, uid: user.id };
      } catch (error) {
        return this.handleError(error);
      }
    },

    // 记录用户登录信息
    async loginLog() {
      try {
        // const ip = await getIpAddress();
        const deviceInfo = getDetailedInfo();
        const data = {
          login_ip: "127.0.0.1",
          ...this.formatDeviceInfo(deviceInfo),
        };
        await recordLog(data);
      } catch (error) {
        this.handleError(error);
      }
    },

    // 获取用户权限菜单
    async GetMenu() {
      try {
        const res = await get_menu({ user_id: this.userinfo.id });
        if (res && res.status === 200) {
          this.routerResult = res.data;
          this.menus = this.handelMenuTree(
            JSON.parse(JSON.stringify(res.data)),
            0
          );
          return res.data;
        } else {
          return this.handleError("拉取菜单失败");
        }
      } catch (error) {
        return this.handleError(error);
      }
    },

    // 递归处理菜单树
    handelMenuTree(menus, parentId) {
      return menus
        .filter((item) => item.parent_id === parentId && item.isShow === 1)
        .map((item) => {
          const children = this.handelMenuTree(menus, item.id);
          if (children.length) {
            item.children = children;
          }
          return item;
        });
    },

    // 更新用户信息
    setUserInfo(data) {
      this.userinfo = data;
    },

    // 重置用户信息
    clearUserData() {
      this.$reset();
      localStorage.removeItem("PINIA:user");
    },

    // 错误处理函数，统一显示错误信息
    handleError(error) {
      const errorMessage =
        error?.response?.data?.message || error.message || "请求失败";
      showMessage("error", errorMessage);
      return { type: false, uid: null };
    },

    // 格式化设备信息，避免重复代码
    formatDeviceInfo(deviceInfo) {
      return Object.keys(deviceInfo).reduce((acc, key) => {
        if (key !== "device") {
          acc[`login_${key}`] = deviceInfo[key];
        }
        return acc;
      }, {});
    },
  },
  getters: {
    user_id(state) {
      return state.userinfo.id;
    },
  },
});
